package com.bfl.sa.sys.group.service;

import com.bfl.sa.common.entity.search.SearchOperator;
import com.bfl.sa.common.entity.search.Searchable;
import com.bfl.sa.common.service.BaseService;
import com.bfl.sa.sys.group.entity.Group;
import com.bfl.sa.sys.group.mapper.GroupMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class GroupService extends BaseService<Group, Long> {

    @Resource
    private GroupMapper groupMapper;

    @Autowired
    private GroupRelationService groupRelationService;

    public Set<Map<String, Object>> findIdAndNames(Searchable searchable, String groupName) {

        searchable.addSearchFilter("name", SearchOperator.like, groupName);

        return Sets.newHashSet(
                super.findPage(searchable).getList().stream().map(input -> {
                    Map<String, Object> data = Maps.newHashMap();
                    data.put("label", input.getName());
                    data.put("value", input.getId());
                    return data;
                }).collect(Collectors.toList())
        );
    }

    /**
     * 获取可用的的分组编号列表
     */
    public Set<Long> findShowGroupIds(Long userId, Set<Long> organizationIds) {
        Set<Long> groupIds = Sets.newHashSet();
        groupIds.addAll(groupMapper.findDefaultGroupIds());
        groupIds.addAll(groupRelationService.findGroupIds(userId, organizationIds));

        //TODO 如果分组数量很多 建议此处查询时直接带着是否可用的标识去查
        for (Group group : super.findList()) {
            if (Boolean.FALSE.equals(group.getShow())) {
                groupIds.remove(group.getId());
            }
        }

        return groupIds;
    }
}
